package com.zige.zige.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zige.zige.R;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.FileSizeUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.view.togglebutton.ToggleButton;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Fei on 2015/11/5.
 *
 */
public class SettingCenterActivity extends BaseActivity implements View.OnClickListener{

    private LinearLayout lay_back;
    private TextView tv_titlet;
    private ToggleButton gesture_button,gesture_remind;
    private boolean isCheck = true;
    private Activity activity;
    private Button btn_exit;
    private TextView tv_ceach_size,tv_version;

    private RelativeLayout lay_modifypassword,lay_modifysafetypassword,lay_clear_ceachsize,lay_user_agreement;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_settingcenter);
        activity = this;
        initView();
//        close();

    }
    private void initView(){
        lay_back = serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(this);
        tv_titlet= serchViewById(R.id.title_name);
        tv_titlet.setText("设置中心");
        btn_exit = serchViewById(R.id.btn_exit);
        if(application.isLogin()){
            btn_exit.setVisibility(View.VISIBLE);
        }else {
            btn_exit.setVisibility(View.GONE);
        }
        btn_exit.setOnClickListener(this);
        lay_modifypassword = serchViewById(R.id.lay_modifypassword);
        if(application.isLogin()){
            lay_modifypassword.setVisibility(View.VISIBLE);
        }else {
            lay_modifypassword.setVisibility(View.GONE);
        }
        lay_modifypassword.setOnClickListener(this);

        lay_modifysafetypassword = serchViewById(R.id.lay_modifysafetypassword);

        lay_modifysafetypassword.setOnClickListener(this);
        gesture_button = serchViewById(R.id.gesture_button);

        boolean on = (boolean) SharedPreferencesUtils.getValue(activity, SharedPreferencesUtils.gesture_toggle, true);
        if(on) {
            gesture_button.setToggleOn();
        }else{
            gesture_button.setToggleOff();
        }

        gesture_button.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                if (on) {
                    SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.gesture_toggle, true);
                } else {
                    SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.gesture_toggle, false);
                }
            }
        });

        tv_ceach_size = serchViewById(R.id.tv_ceach_size);
        tv_ceach_size.setText(FileSizeUtils.getAutoFileOrFilesSize("storage/emulated/0/LittleZebra"));
        lay_clear_ceachsize = serchViewById(R.id.lay_clear_ceachsize);
        lay_clear_ceachsize.setOnClickListener(this);

        gesture_remind = serchViewById(R.id.gesture_remind);
        gesture_remind.setToggleOn();

        lay_user_agreement = serchViewById(R.id.lay_user_agreement);
        lay_user_agreement.setOnClickListener(this);
        tv_version = serchViewById(R.id.tv_version);
        tv_version.setText("V"+SystemUtils.getVersionName(activity).trim());

    }

    private void close(){
        boolean on = (boolean) SharedPreferencesUtils.getValue(activity, SharedPreferencesUtils.gesture_toggle, false);
        if (on) {
            gesture_button.setToggleOff();

        } else {
            gesture_button.setToggleOn();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_back:
                SettingCenterActivity.this.finish();
                overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
                break;
            case R.id.btn_exit:
                exited();
                break;
            case R.id.lay_modifypassword:
                startActivity(new Intent(activity,ModifyPasswordActivity.class));
                finish();
                overridePendingTransition(R.anim.l2r_in, R.anim.l2r_out);
                break;
            case R.id.lay_modifysafetypassword:

                break;
            case R.id.lay_clear_ceachsize:
                AlertDialog.Builder builder = new AlertDialog.Builder(SettingCenterActivity.this);
                builder.setMessage("确定要清除当前缓存吗？");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        File file = new File(Environment.getExternalStorageDirectory() + "/Littlezebra");
                        deleteAllFiles(file);
                        tv_ceach_size.setText(FileSizeUtils.getAutoFileOrFilesSize("storage/emulated/0/LittleZebra/video"));
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                break;
            case R.id.lay_user_agreement:
                startActivity(new Intent(activity, UserAgreementActivity.class));
                overridePendingTransition(R.anim.l2r_in, R.anim.l2r_out);
                break;


        }
    }


    private void exited() {
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingCenterActivity.this);
        builder.setMessage(R.string.exit_message);
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                logout();

            }
        });
        builder.setNegativeButton(R.string.btn_cancle, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**清除缓存*/
    private void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }


    private void  logout(){
        String deviceId = SystemUtils.getDeviceKey(activity);
        String uid = application.getUserInfo().userID;
        HashMap<String,String> params = new HashMap<>();
        params.put("deviceId",deviceId);
        params.put("uid", uid);
        showLoadingDialog();
        Log.e("wu","    "+deviceId+"   "+uid);
        TaskExecutor.getInstance().execute(new PostRequestTask(params,activity, UrlConsts.USER_LOGOUT) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    if(code==0000){
                        closeLoadingDialog();
                        application.setUserInfo(null);
                        SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_state, false);
                        SharedPreferencesUtils.saveValue(activity
                                , SharedPreferencesUtils.user_safetyLockPassword, false);
                        startActivity(new Intent(activity, HomedActivity.class));
                        activity.finish();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            @Override
            protected void handleError() {
                super.handleError();
                closeLoadingDialog();
                startActivity(new Intent(activity, HomedActivity.class));
                activity.finish();
            }
        });

    }

}

